package com.sym.architecture.ext

import android.content.Context
import android.os.Handler
import android.os.Message
import androidx.appcompat.app.AlertDialog
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import java.lang.Exception
import java.util.prefs.Preferences
import kotlin.coroutines.resumeWithException

suspend fun Context.alert(title: String, msg: String): Boolean =
    suspendCancellableCoroutine { cancellableCoroutine ->
        AlertDialog.Builder(this)
            .setNeutralButton("No") { dialog, _ ->
                dialog.dismiss()
                cancellableCoroutine.resume(false, null)
            }.setNegativeButton("Yes") { dialog, _ ->
                dialog.dismiss()
                cancellableCoroutine.resume(true, null)
            }.setTitle(title)
            .setMessage(msg).setOnCancelListener {
                cancellableCoroutine.resume(false, null)
            }.create()
            .also { dialog ->
                cancellableCoroutine.invokeOnCancellation {
                    //协程取消后将dialog取消
                    dialog.dismiss()
                }
            }.show()

    }

@ExperimentalCoroutinesApi
suspend fun <T> Handler.run(block: () -> T): T =
    suspendCancellableCoroutine<T> { cancellableContinuation ->
        post {
            try {
                cancellableContinuation.resume(block(), null)
            } catch (t: Throwable) {
                cancellableContinuation.resumeWithException(t)
            }
        }

    }

suspend fun <T> Handler.runDelay(delay: Long, block: () -> T): T =
    suspendCancellableCoroutine { cancellableContinuation ->
        var msg = Message.obtain(this) {
            try {
                cancellableContinuation.resume(block(), null)
            } catch (e: Exception) {
                cancellableContinuation.resumeWithException(e)
            }
        }
        msg.obj = cancellableContinuation

        cancellableContinuation.invokeOnCancellation {
            removeCallbacksAndMessages(cancellableContinuation)
        }

        sendMessageDelayed(msg, delay)
    }

